<?php
session_start();

class CAlbumController extends CController {
	
	public function __construct() {
		parent::__construct();
	}
	
	public function index() {
		$categories = CSingle::getInstance('CCategoryModel', 'getCategories');
		$this->_view->set('categories', $categories);
		$cat_names = array();
		foreach ($categories as $category) {
			$cat_names[$category['cat_id']] = $category['cat_name'];
		}
		$this->_view->set('cat_names', $cat_names);
		
		$this->_view->set('albums', $this->_model->findAll('*', null, 'album_id DESC'));
		$this->_view->display();
	}
	public function add() {
		$this->_view->set('categories', CSingle::getInstance('CCategoryModel', 'getCategories'));
		$this->_view->display();
	}
	public function insert() {
		$album_id = $this->_model->create($_POST);
		$finfo = new finfo(FILEINFO_MIME);
		$image = new CAlbumImageModel();
		$image->album_id = $album_id;
		$album_path = APP_PATH.'/../upload/album/'.$album_id;
		if (!is_dir($album_path)) {
			mkdir($album_path, 0777);
		}
		foreach ($_SESSION['file_info'] as $file_id=>$file_info) {
			$file_ids = explode('.', $file_id);
			$image->img_title = $file_ids[0];
			$image->img_name = $file_ids[0];
			$image->img_type = $finfo->buffer($file_info);
			$image->img_src = '/upload/album/'.$album_id.'/'.$file_id;
			$image->create();
			file_put_contents($album_path.'/'.$file_id, $file_info);
			unset($_SESSION['file_info'][$file_id]);
		}
		$this->message('添加成功', 0, $this->url('album'));
	}
	public function edit() {
		$this->_view->set('categories', CSingle::getInstance('CCategoryModel', 'getCategories'));
		$this->_view->set('album', $this->_model->find($_GET['album_id']));
		$image_model = new CAlbumImageModel();
		$this->_view->set('images', $image_model->findAll('*', 'album_id = '.$_GET['album_id']));
		$this->_view->display();
	}
	public function update() {
		$this->_model->save($_POST);
		$this->message('更新成功');
	}
	public function delete() {
		$this->_model->delete($_GET['album_id']);
		$this->message('删除成功');
	}
}
